<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件后缀" prop="postfix">
        <el-input
          v-model="queryParams.postfix"
          placeholder="请输入文件后缀"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="桶id" prop="bucketId">
        <el-input
          v-model="queryParams.bucketId"
          placeholder="请输入桶id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['file:resource:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['file:resource:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['file:resource:export']"
          >导出</el-button
        > -->
        <!-- <el-upload
          class="upload-demo"
          :action="uploadFileUrl"
          :on-preview="handlePreview"
          :on-success="success"
          :headers="headers"
          :before-upload="beforeUpload"
          :file-list="fileList"
          ref="upload"
        >
          <el-button size="small" type="primary" @click="clearFile()"
            >点击上传</el-button
          >
        </el-upload> -->
        <el-upload
          action
          class="upload-demo"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleChange"
        >
          <!-- <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

        <!-- 进度显示 -->
        <div class="progress-box">
          <span>上传进度：{{ percent.toFixed() }}%</span>
          <el-button type="primary" size="mini" @click="handleClickBtn">{{
            upload | btnTextFilter
          }}</el-button>
        </div>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="resourceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="false" label="主键" align="center" prop="id" />
      <el-table-column label="文件编号" align="center" prop="id" />
      <el-table-column label="桶id" align="center" prop="bucketId" />
      <el-table-column label="文件MD5值" align="center" prop="md5" />
      <el-table-column label="文件名称" align="center" prop="name" />
      <el-table-column label="文件后缀" align="center" prop="postfix" />
      <el-table-column
        label="文件上传路径"
        align="center"
        prop="uploadPath"
        width="320"
      />
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['file:resource:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-hasPermi="['file:resource:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleUpload(scope.row)"
            >下载</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import qs from 'qs'
import {
  listResource,
  getResource,
  delResource,
  addResource,
  updateResource,
  exportResource
} from '@/api/file/resource'
import { downLoadZip } from '@/utils/zipdownload'
import { getToken } from '@/utils/auth'
export default {
  name: 'Resource',
  components: {},
  filters: {
    btnTextFilter(val) {
      return val ? '暂停' : '继续'
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      percent: 0,
      videoUrl: '',
      upload: true,
      percentCount: 0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件资源表格数据
      resourceList: [],
      // 弹出层标题
      title: '',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 是否显示弹出层
      open: false,
      fileList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/file/resource', // 上传的地址
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        postfix: undefined,
        bucketId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      fileName: '',
      id: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(
        c
      ) {
        var r = (Math.random() * 16) | 0
        var v = c === 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
    },
    async handleChange(file) {
      if (!file) return
      this.percent = 0
      console.log(file)
      // 获取文件并转成 ArrayBuffer 对象
      const fileObj = file.raw
      this.fileName = file.name

      // 将文件按固定大小（2M）进行切片，注意此处同时声明了多个常量
      const chunkSize = 2097152
      const chunkList = [] // 保存所有切片的数组
      const chunkListLength = Math.ceil(fileObj.size / chunkSize) // 计算总共多个切片
      // suffix = /\.([0-9A-z]+)$/.exec(fileObj.name)[1]; // 文件后缀名

      // 根据文件内容生成 hash 值
      // const spark = new SparkMD5.ArrayBuffer();
      // spark.append(buffer);
      // const hash = spark.end();

      // 生成切片，这里后端要求传递的参数为字节数据块（chunk）和每个数据块的文件名（fileName）
      let curChunk = 0 // 切片时的初始位置
      for (let i = 0; i < chunkListLength; i++) {
        const item = {
          chunk: fileObj.slice(curChunk, curChunk + chunkSize)
          // fileName: `${hash}_${i}.${suffix}` // 文件名规则按照 hash_1.jpg 命名
        }
        curChunk += chunkSize

        chunkList.push(item)
      }
      this.chunkList = chunkList // sendRequest 要用到
      console.log(this.chunkList)
      // this.hash = hash; // sendRequest 要用到
      this.sendRequest()
    },

    // 发送请求
    sendRequest() {
      this.guid()
      this.id = this.guid()
      const requestList = [] // 请求集合
      this.chunkList.forEach((item, index) => {
        const fn = () => {
          const formData = new FormData()
          formData.append('file', item.chunk)
          formData.append('filename', this.fileName)
          formData.append('guid', this.id)
          formData.append('chunk', index)
          return request({
            url: '/file/zip/add',
            method: 'post',
            data: formData
          }).then(() => {
            // 成功
            if (this.percentCount === 0) {
              // 避免上传成功后会删除切片改变 chunkList 的长度影响到 percentCount 的值
              this.percentCount = 100 / this.chunkList.length
            }
            this.percent += this.percentCount // 改变进度
            this.chunkList.splice(index, 1) // 一旦上传成功就删除这一个 chunk，方便断点续传
          })
        }
        requestList.push(fn)
      })

      let i = 0 // 记录发送的请求个数
      // 文件切片全部发送完毕后，需要请求 '/merge' 接口，把文件的 hash 传递给服务器
      const complete = () => {
        request({
          url: '/file/zip/merge',
          method: 'get',
          params: { guid: this.id, fileName: this.fileName }
        }).then(res => {
          if (res.data.code === 0) {
            // 请求发送成功
          }
        })
      }
      const send = async() => {
        console.log(i, requestList.length)
        if (!this.upload) return
        if (i >= requestList.length) {
          // 发送完毕
          complete()
          return
        }
        await requestList[i]()
        i++
        send()
      }
      send() // 发送请求
    },

    // 按下暂停按钮
    handleClickBtn() {
      this.upload = !this.upload
      // 如果不暂停则继续上传
      if (this.upload) this.sendRequest()
    },
    clearFile() {
      this.$refs.upload.clearFiles()
    },
    // 下载
    handleUpload(row) {
      downLoadZip('/file/resource/download?id=' + row.id, 'cms-admin')
    },
    /** 查询文件资源列表 */
    getList() {
      this.loading = true
      listResource(this.queryParams).then(response => {
        this.resourceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        number: undefined,
        md5: undefined,
        name: undefined,
        postfix: undefined,
        bucketId: undefined,
        uploadPath: undefined,
        version: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id || this.ids
      getResource(id).then(response => {
        this.loading = false
        this.form = response.data
        this.open = true
        this.title = '修改文件资源'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateResource(this.form)
              .then(response => {
                this.buttonLoading = false
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .catch(() => {
                this.buttonLoading = false
              })
          } else {
            addResource(this.form).then(response => {
              this.buttonLoading = false
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm(
        '是否确认删除文件资源编号为"' + ids + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.loading = true
          return delResource(ids)
        })
        .then(() => {
          this.loading = false
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {
          this.loading = false
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有文件资源数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true
          return exportResource(queryParams)
        })
        .then(response => {
          this.download(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    }
  }
}
</script>
<style scoped>
.progress-box {
  box-sizing: border-box;
  width: 360px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding: 8px 10px;
  background-color: #ecf5ff;
  font-size: 14px;
  border-radius: 4px;
}
</style>
